//
// Created by Administrator on 2021/7/1.
//

//给定一个二叉树，返回其节点值自底向上的层序遍历。 （即按从叶子节点所在层到根节点所在的层，逐层从左向右遍历）

#include <vector>
#include <queue>
#include <iostream>
#include <algorithm>
using namespace std;

// Definition for a binary tree node.
struct TreeNode {
    int val;
    TreeNode *left;
    TreeNode *right;

    TreeNode() : val(0), left(nullptr), right(nullptr) {}

    TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}

    TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
};

class Solution {
public:
    vector<vector<int>> levelOrderBottom(TreeNode *root) {
        vector<vector<int>>ans;
        if (root == nullptr) return ans;
        queue<TreeNode*>q;
        q.push(root);
        while (!q.empty()){
            auto  levelSize = q.size();
            ans.emplace_back();
            for (int i =0;i<levelSize;++i){
                auto p = q.front();
                q.pop();
                ans.back().emplace_back(p->val);
                if (p->left!= nullptr)  q.push(p->left);
                if (p->right!= nullptr)  q.push(p->right);
            }
        }
        reverse(ans.begin(),ans.end());
        return ans;
    }
};

int main() {
    auto n1 = TreeNode(3), n2 = TreeNode(9), n3 = TreeNode(20),
            n4 = TreeNode(15), n5 = TreeNode(7);
    n1.left = &n2;
    n1.right = &n3;
    n3.left = &n4;
    n3.right = &n5;
    Solution sol;
    auto ans = sol.levelOrderBottom(&n1);
    for (auto &x:ans) {
        for (auto &y:x) {
            cout << y;
            cout << " ";
        }
        cout << endl;
    }

    return 0;
}
